#include "clientregister.h"
#include "ui_clientregister.h"
#include "newpasswordsure.h"

clientRegister::clientRegister(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::clientRegister)
{
    ui->setupUi(this);
}

clientRegister::~clientRegister()
{
    delete ui;
}

//点击注册界面的确认按钮
void clientRegister::on_regEnterPushButton_clicked()
{
    QString newAccount = ui->newALineEdit->text();      //获取账号输入框文本
    QString newPassword = ui->newPLineEdit->text();     //获取密码输入框文本

    //判断账号和密码是否为空
    if(newAccount.isEmpty() || newPassword.isEmpty()){
        QMessageBox::warning(this, "错误", "账号和密码不能为空");
        return;
    }

    newPasswordSure newPasswordDialog(newPassword);                //创建个新密码确认界面
    newPasswordDialog.setGeometry(this->geometry());               //新创建的界面与当前界面重合

    //按下了确认键
    if(newPasswordDialog.exec() == QDialog::Accepted)
    {

        QSqlDatabase db = QSqlDatabase::database(); // 使用主界面的数据库连接
        if(!db.isOpen())        //数据库没有打开
        {
            QMessageBox::critical(this, "错误", "数据库未连接");
            return;
        }

        QSqlQuery query;        //创建一个数据库查询对象
        query.prepare("INSERT INTO users (account, password) VALUES (:account, :password)"); // 查询语句SQL
        query.bindValue(":account", newAccount);        //绑定账号键
        query.bindValue(":password", newPassword);      //绑定密码键

        //数据库成功执行
        if(query.exec())
        {

            QMessageBox::information(this, "成功", "注册成功");       //提示注册成功
            this->close();          //关闭
        }
        else
        {
            QString error =  query.lastError().text();      //获取错误信息
            if(error.contains("Duplicate entry"))       //如果错误信息中包含重复条目
            {
                QMessageBox::warning(this, "错误", "账号已存在");          //错误提示
            }
            else
            {
                QMessageBox::critical(this, "失败", "错误: " + error);    //显示失败

            }

        }

    }

}

void clientRegister::on_cancelPushButton_clicked()
{
    this->close();
}
